//@author A0101119Y
#include "GCalVariableMgr.h"

using namespace Poco::JSON;
using namespace Poco::Dynamic;
using namespace Twentyfifth;
using namespace std;

const int GCalVariableMgr::POS_START_OF_LABEL = 0;
const string GCalVariableMgr::LABEL_CLIENT_ID = "client_id";
const string GCalVariableMgr::LABEL_CLIENT_SECRET = "client_secret";
const string GCalVariableMgr::MESSAGE_FILE_CORRUPTED = "ERROR: Google file data corrupted; file purged.";
const string GCalVariableMgr::VALUE_CLIENT_ID = "583554430715-5lbfjlbtgilqvq6s9lp2kq27injd3m87.apps.googleusercontent.com";
const string GCalVariableMgr::VALUE_CLIENT_SECRET = "8jgwq1SviYs4xo7Ogfo1sk0Q";

GCalVariableMgr::GCalVariableMgr() {
	readMapFromFile();
	variables[LABEL_CLIENT_ID] = VALUE_CLIENT_ID;
	variables[LABEL_CLIENT_SECRET] = VALUE_CLIENT_SECRET;
}

GCalVariableMgr::~GCalVariableMgr() {
	readMapFromFile();
	writeMapToFile();
}

string GCalVariableMgr::getValue(string key) {
	return variables.at(key);
}

void GCalVariableMgr::setValue(string key, string value) {
	variables[key] = value;
	writeMapToFile();
	return;
}

void GCalVariableMgr::readMapFromFile() {
	ifstream file(FILE_GOOGLE, fstream::in);
	stringstream strStream;
	if (file) {
		strStream << file.rdbuf();
		file.close();
	}
	string json = strStream.str();
	if (json != BLANK_STRING) {
		try {
			variables = parser.parseJsonToMap(json);
		}
		catch (Poco::Exception&) {
			cerr << MESSAGE_FILE_CORRUPTED << endl;
			clearAll();
		}
	}
	file.close();
}

void GCalVariableMgr::writeMapToFile() {
	Object mapObject;
	ofstream file(FILE_GOOGLE, fstream::out | fstream::ate);
	for (map<string, string>::iterator it = variables.begin(); it != variables.end(); it++) {
		string key = it->first;
		if ((key == LABEL_CLIENT_ID) || (key == LABEL_CLIENT_SECRET)) { // ignore client ID and secret
			continue;
		}
		string value = it->second;
		mapObject.set(key, value);
	}
	mapObject.stringify(file);
	file.close();
}

void GCalVariableMgr::clearAll() {
	variables.clear();
	variables[LABEL_CLIENT_ID] = VALUE_CLIENT_ID;
	variables[LABEL_CLIENT_SECRET] = VALUE_CLIENT_SECRET;
	writeMapToFile();
}

bool GCalVariableMgr::exists(string key) {
	try {
		variables.at(key);
		return true;
	}
	catch (exception&) {
		return false;
	}
}